package com.ebt.m.wiki.view;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ebt.m.R;
import com.ebt.m.utils.StringUtils;
import com.ebt.m.utils.UIHelper;
import com.ebt.m.view.InputDialog;

/**
 * 保险利益View
 *
 * @author Michael.li
 */
public class WikiTab2InputView extends RelativeLayout implements OnClickListener {
    private TextView mTitle;
    private ImageView mBtnMinus, mBtnPlus;
    private RelativeLayout mPlusFrame, mMinusFrame;
    private EditText mInputView;

    private double mValue;// Tim
    private double maxValue;// Tim
    private double minValue;// Tim
    private double stepValue;// Tim
    private boolean isBaoE;
    private boolean isBaoFEI;
    private boolean isBaoFEIZhuijia;
    private Context ctx;
    private boolean mUseDiff;

    public WikiTab2InputView(Context context) {
        this(context, null);
    }

    public WikiTab2InputView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public WikiTab2InputView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        ctx = context;
        inflate(context, getLayoutResource(), this);
        mTitle = (TextView) findViewById(R.id.wiki_input_title);
        mBtnMinus = (ImageView) findViewById(R.id.wiki_input_minus);
        mBtnPlus = (ImageView) findViewById(R.id.wiki_input_plus);
//		mInputView = (EditText) findViewById(R.id.wiki_input_value);
        mPlusFrame = (RelativeLayout) findViewById(R.id.wiki_input_plus_frame);
        mMinusFrame = (RelativeLayout) findViewById(R.id.wiki_input_minus_frame);
    }

    /**
     * layout id
     *
     * @return
     */
    protected int getLayoutResource() {
        return R.layout.wiki_view_tab2_input;
    }

    public void updateValue(double value) {
        mValue = value;
        setValue();
    }

    /**
     * @param title     条目名
     * @param value     条目值
     * @param maxValue  条目最大值
     * @param minValue  条目最小值
     * @param stepValue 步值
     * @param enabled   是否激活状态
     * @author Tim
     */
    public void setData(String title, double value, double maxValue, double minValue, double stepValue, boolean enabled, boolean useDiff, String unit) {
        this.maxValue = maxValue;
        this.minValue = minValue;
        this.stepValue = stepValue;
        this.isBaoE = title.indexOf("保额") != -1;
        this.isBaoFEI = title.indexOf("保费") != -1;
        this.isBaoFEIZhuijia = title.indexOf("追加保费") != -1;
        this.mUseDiff = useDiff;

        mTitle.setText(title + "(" + unit + ")");
        mMinusFrame.setVisibility(enabled ? View.VISIBLE : View.GONE);
        mPlusFrame.setVisibility(enabled ? View.VISIBLE : View.GONE);

        if (enabled) {
            mInputView = (EditText) findViewById(R.id.wiki_input_value);
            findViewById(R.id.wiki_input_value2).setVisibility(View.GONE);
        } else {
            mInputView = (EditText) findViewById(R.id.wiki_input_value2);
            findViewById(R.id.wiki_input_value).setVisibility(View.GONE);
        }
        mInputView.setVisibility(View.VISIBLE);

        onSetEnabled(this, enabled);
        setupListener();
        if (enabled) {
            mValue = checkValue(value);
            mInputView.setFocusable(false);
            mInputView.setFocusableInTouchMode(false);
            mInputView.setOnClickListener(this);
        }
        setValue();
    }

    public void onSetEnabled(View container, boolean enabled) {
        mInputView.setEnabled(enabled);
        if (enabled) {
            // mInputView.setTextColor(Color.BLACK);
        } else {
            View vv = container.findViewById(R.id.wiki_input_container);
            if (vv != null) {
//				vv.setBackgroundColor(Color.parseColor("#999999"));
                vv.setBackgroundColor(getResources().getColor(R.color.full_transparent));
            }
        }
    }

    public static void setCompoundDrawableLeft(TextView view, int resid) {
        Drawable icon = ContextCompat.getDrawable(view.getContext(), resid);

        int width = 60;

        icon.setBounds(0, 0, width, width * 3 / 4);
//		view.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null);
        view.setCompoundDrawables(icon, null, null, null);
    }

    /**
     * setData方法之后调用方可生效
     *
     * @param allowed
     */
    public void setKeyboardAllowed(boolean allowed) {
        if (!allowed) {
            mInputView.setOnClickListener(null);
        } else {
//			setCompoundDrawableLeft(mInputView, R.drawable.hardware_keyboard);
            //setCompoundDrawableLeft(mInputView, R.drawable.ic_wiki_keyboard);
        }
    }

    private void setValue() {
        String value = StringUtils.format2String(mValue);
        if (mValue <= 0) {
            value = "不可保";
            if (isBaoFEIZhuijia && "不可保".equalsIgnoreCase(value)) {
                value = "0";
            }
            mInputView.setText(value);
            return;
        }
        value = StringUtils.addComma(value);
        if (isBaoE) {
            int last = value.lastIndexOf(".");
            if (last != -1) {
                value = value.substring(0, last);
            }
        }
        mInputView.setText(value);

    }

    // private String getFormatValue(double value)
    // {
    // DecimalFormat df = new DecimalFormat("0.00");
    // Double d = Double.valueOf(value);
    // return df.format(d);
    // }

    /**
     * 检查用户输入或者点击加减号获得的保额或者保费值，并自动修正错误值
     *
     * @param temp
     * @return
     */
    private double checkValue(double temp) {
        double origin = temp;
        // maxValue小于0时，说明无上限
        if (maxValue < 0) {
            if (temp < minValue) {
                UIHelper.makeToast(ctx, mTitle.getText().toString().trim() + "不能小于" + minValue);
                return minValue;
            }
            if (mUseDiff) {
                temp = Math.round(temp / stepValue) * stepValue;
                if (temp != origin) {
                    UIHelper.makeToast(ctx, (isBaoE ? "保额" : "保费") + "已根据投保规则自动调整");
                }
            }
        } else {
            if (mUseDiff) {
                temp = Math.round(temp / stepValue) * stepValue;
                if (temp != origin) {
                    UIHelper.makeToast(ctx, (isBaoE ? "保额" : "保费") + "已根据投保规则自动调整");
                }
            }
            if (temp > maxValue) {
                temp = maxValue;
                UIHelper.makeToast(ctx, mTitle.getText().toString().trim() + "不能大于" + StringUtils.format2String(temp));
            } else if (temp < minValue) {
                temp = minValue;
                UIHelper.makeToast(ctx, mTitle.getText().toString().trim() + "不能小于" + minValue);
            }
        }
        return temp;
    }

    private void setupListener() {
//		mBtnMinus.setOnClickListener(this);
//		mBtnPlus.setOnClickListener(this);
        mPlusFrame.setOnClickListener(this);
        mMinusFrame.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        v.setEnabled(false);
        switch (v.getId()) {
            case R.id.wiki_input_minus_frame:
                mValue = checkValue(mValue - stepValue);
                if (stepValue > 0 && mValue >= stepValue) {
                    mValue = mValue - mValue % stepValue;
                }
                setValue();
                if (onValueChangedListener != null) {
                    onValueChangedListener.onValueChanged(mValue);
                }
                break;
            case R.id.wiki_input_plus_frame:
                mValue = checkValue(mValue + stepValue);
                if (stepValue > 0 && mValue >= stepValue) {
                    mValue = mValue - mValue % stepValue;
                }
                setValue();
                if (onValueChangedListener != null) {
                    onValueChangedListener.onValueChanged(mValue);
                }
                break;
            case R.id.wiki_input_value:
//                showInputDialog();
                showInputCustomDialog();
                break;
            default:
                break;
        }
    }

    public void setEnabled() {
        mBtnMinus.setEnabled(true);
        mBtnPlus.setEnabled(true);
        mInputView.setEnabled(true);
        mPlusFrame.setEnabled(true);
        mMinusFrame.setEnabled(true);
    }

    private void showInputDialog() {
        LayoutInflater li = LayoutInflater.from(ctx);
        View promptsView = li.inflate(R.layout.wiki_dialog_input, null);
        final EditText userInput = (EditText) promptsView.findViewById(R.id.input);
        userInput.setText(mInputView.getText().toString().trim().replace(",", ""));
        userInput.setSelection(userInput.getText().length());
        // set dialog message
        CharSequence title = "请输入" + mTitle.getText().toString().trim();
        AlertDialog dialog = new AlertDialog.Builder(ctx).setView(promptsView).setCancelable(false).setTitle(title).setPositiveButton("确定", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                String value = userInput.getText().toString().trim();
                if (value.length() == 0) {
                    UIHelper.keepDialog(dialog);
                    UIHelper.makeToast(getContext(), mTitle.getText().toString().trim() + "不能为空");
                    return;
                }
                double temp = Double.parseDouble(value);
                if (onValueChangedListener != null && mValue != temp) {
                    mValue = checkValue(temp);
                    setValue();
                    onValueChangedListener.onValueChanged(mValue);
                }
                setEnabled();
                UIHelper.distoryDialog(dialog);
            }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                setEnabled();
                UIHelper.distoryDialog(dialog);
            }
        }).create();
        dialog.setOnDismissListener(new OnDismissListener() {

            @Override
            public void onDismiss(DialogInterface dialog) {
                UIHelper.hideSoftInputFromWindow(mTitle);
            }
        });
        dialog.show();
    }

    private void showInputCustomDialog() {
        String title = "请输入" + mTitle.getText().toString().trim();

        InputDialog dialog = new InputDialog(ctx);
        dialog.setTitle(title);
        dialog.setEdit(mInputView.getText().toString().trim().replace(",", ""));
        dialog.setPositiveButton("确定", new OnClickListener() {
            @Override
            public void onClick(View v) {
                String value = dialog.getEditString();
                if (value.length() == 0) {
                    UIHelper.makeToast(getContext(), mTitle.getText().toString().trim() + "不能为空");
                    return;
                }
                double temp = Double.parseDouble(value);
                if (onValueChangedListener != null && mValue != temp) {
                    mValue = checkValue(temp);
                    setValue();
                    onValueChangedListener.onValueChanged(mValue);
                }
                setEnabled();
                dialog.dismiss();
            }
        });
        dialog.setNegativeButton("取消", new OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                setEnabled();
            }
        });
        dialog.getDialog().setOnDismissListener(new OnDismissListener() {

            @Override
            public void onDismiss(DialogInterface dialog) {
                UIHelper.hideSoftInputFromWindow(mTitle);
            }
        });


    }

    public interface OnValueChangedListener {
        /**
         * 值改变
         *
         * @param value
         */
        void onValueChanged(double value);

        /**
         * 输入无效
         */
        void onInputInvalid();
    }

    private OnValueChangedListener onValueChangedListener;

    public void setOnValueChangedListener(OnValueChangedListener onValueChangedListener) {
        this.onValueChangedListener = onValueChangedListener;
    }
}